package com.example.car.service.Impl;

import com.example.car.entity.Car;
import com.example.car.entity.Order;
import com.example.car.mapper.OrderMapper;
import com.example.car.service.CarService;
import com.example.car.service.OrderService;
import com.example.car.service.UserService;
import com.example.car.utils.DateFormatUtil;
import com.example.car.vo.CarDirverVo;
import com.example.car.vo.OrderVo;
import com.example.car.vo.TimeConditionVo;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CarService carService;

    @Override
    public List<Order> list(String userId, int page, int limit) {
        return orderMapper.list(userId, page, limit);
    }

    @Override
    @Transactional
    public boolean addOrder(OrderVo ordervo, String userId, String orderId) {
        Order order = new Order();

        Car car = carService.getCarById(ordervo.getCarId());

        order.setUserId(userId);
        BeanUtils.copyProperties(ordervo, order);
        CarDirverVo carDirverVo = new CarDirverVo();
        carDirverVo.setCarId(ordervo.getCarId());
        carDirverVo.setDriverId(ordervo.getDriverId());
        order.setCarDirver(carDirverVo);
        order.setBeginTime(DateFormatUtil.getFormatTime(ordervo.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        if (ordervo.getRentType() == 1) {
            order.setRentStandard(car.getRentStandardDay());
        } else {
            order.setRentStandard(car.getRentStandardMouth());
        }
        order.setOrderNo(orderId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + ordervo.getDays());
        Date endTime = calendar.getTime();
        order.setEndDate(DateFormatUtil.getFormatTime(endTime, "yyyy-MM-dd HH:mm:ss"));
        orderMapper.addOrder(order);
        carService.rentCar(ordervo.getCarId());
        return true;
    }

    @Override
    public boolean payOrder(String orderId) {
        return orderMapper.payOrder(orderId);
    }

    @Override
    public Double orderStatistics(TimeConditionVo timeConditionVo) {
        return orderMapper.orderStatistics(timeConditionVo);
    }

    @Override
    public Long getTotal(String userId) {
        return orderMapper.getTotal(userId);
    }
}
